package com.project.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtils {
    //将工厂对象定义为静态变量
    private static SqlSessionFactory sqlSessionFactory;

    //执行一次静态代码块，创建一个工厂对象
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //调用此方法就能返回一个工厂对象，不用多次创建
    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}
